package com.android.task4;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Vector;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


public class HTTPClient {
	
	private final static String url = "http://nimbus.informatik.uni-stuttgart.de/~fapra-android/OSMTiles/";
	private final static int N_THREADS = 1;
	private final static int TIMEOUT = 1000;
	private ThreadPool threadPool;


	public HTTPClient(){
		threadPool = new ThreadPool(N_THREADS);
	}
	
	public Bitmap newRequest(int x, int y, int zoom){
		String urlString =url+zoom+"/"+x+"/"+y+".png";
		Log.i("INFO", "New request to:" + urlString);
		Log.i("INFO", "HTTPRequest running...");
		URL url;
		try {
			url = new URL(urlString);
		
		HttpURLConnection conn= (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setDoOutput(true);
		conn.setReadTimeout(TIMEOUT);
		conn.connect();
		if(conn!=null){		
			httpRequest newReq = new httpRequest(conn);
			threadPool.execute(newReq);
			while(!newReq.isReady()){}
			return newReq.getBitmap();
		}
		else{
			return null;
		}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

		

	
	private class httpRequest implements Runnable{
		HttpURLConnection conn;
		Bitmap bm;
		boolean READY=false;
	
		public httpRequest(HttpURLConnection c){
		conn=c;
		}
		public boolean isReady(){
			return READY;
		}
		
		public  Bitmap getBitmap() {
			// TODO Auto-generated method stub
			return bm;
		}

		public void run() {
			
			try {
					Log.i("info", "Success!");
					InputStream is;
					
					is = conn.getInputStream();
					
					bm = BitmapFactory.decodeStream(is);
					is.close();
					conn.disconnect();
					Log.i("INFO", "...HTTPRequest stopped");
					READY = true;
					if(bm == null){
						Log.i("Info", "Any bitmap was received from server...");
					}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
		
		}
};
	}
 
